#ifndef SAFEMAP_H
#define SAFEMAP_H


#include <QtCore/QtCore>
#include <QtConcurrent/QtConcurrent>

template <class Key, class T>
class SafeMap
{

public:
    SafeMap()
    {

    }
    SafeMap(const SafeMap<Key, T> &other)
    {
        m_map = other.m_map;
    }
    ~SafeMap()
    {
    }

    void insert(const Key& key, const T& value)
    {
        QWriteLocker locker(&m_mutex);
        m_map.insert(key, value);
    }

    const T value(const Key &key, const T& defaultValue = T())
    {
        QReadLocker locker(&m_mutex);
        auto it = m_map.constFind(key);
        if(it != m_map.constEnd())
        {
            return it.value();
        }
        return defaultValue;
    }

    void modify(const Key& akey, std::function<T&(T&)> func)
    {
        QWriteLocker locker(&m_mutex);
        T& value = m_map[akey];
        value = func(value);
    }

    const QMap<Key, T> getMap()
    {
        QReadLocker locker(&m_mutex);
        const auto& temp = m_map;
        return temp;
    }

protected:

private:
    QMap<Key, T> m_map;
    QReadWriteLock m_mutex;
};

#endif // SAFEMAP_H
